package ad.ui 
{
	import ad.events.EventDispatcherExpert;
	import ad.events.SliderEvent;
	
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	[Event(type='SliderEvent.UPDATE', type='ad.events.SliderEvent')]
	[Event(type='SliderEvent.DRAG', type='ad.events.SliderEvent')]
	[Event(type='SliderEvent.DROP', type='ad.events.SliderEvent')]
	
	/**
	 * Slider
	 * @version ActionScript 3.0
	 * @author Adrian C. Miranda
	 * @mail ad@adrianmiranda.com.br
	 */
	public class Slider extends EventDispatcherExpert
	{
		private var _position:Point;
		private var _area:Rectangle;
		
		public function Slider(area:Rectangle, position:Point = null) 
		{
			this.area = area.clone();
			this.position = position ? position.clone() : new Point(0, 0);
			super();
		}
		
		public function get position():Point { return _position.clone(); }
		public function set position(value:Point):void 
		{
			_position.x = Math.max(area.x, Math.min((area.x + area.width), value.x));
			_position.y = Math.max(area.y, Math.min((area.y + area.height), value.y));
			dispatchEvent(new SliderEvent(SliderEvent.UPDATE, percentage, position, offset));
		}
		
		public function get positionX():Number { return position.x }
		public function set positionX(value:Number):void 
		{
			position = new Point(value, positionY);
		}
		
		public function get positionY():Number { return position.y }
		public function set positionY(value:Number):void 
		{
			position = new Point(positionX, value);
		}
		
		public function get percentage():Point 
		{
			var percentX:Number = (position.x - area.x) / area.width;
			var percentY:Number = (position.y - area.y) / area.height;
			percentX = isNaN(percentX) ? 1 : percentX;
			percentY = isNaN(percentY) ? 1 : percentY;
			return new Point(percentX, percentY);
		}
		public function set percentage(value:Point):void 
		{
			position = new Point(area.x + (area.width * value.x), area.y + (area.height * value.y));
			dispatchEvent(new SliderEvent(SliderEvent.UPDATE, percentage, position, offset));
		}
		
		public function get percentageX():Number { return percentage.x; }
		public function set percentageX(value:Number):void 
		{
			percentage = new Point(value, percentageY);
		}
		
		public function get percentageY():Number { return percentage.y; }
		public function set percentageY(value:Number):void 
		{
			percentage = new Point(percentageX, value);
		}
		
		public function get offset():Point 
		{
			var offsetX:Number = (position.x - area.x);
			var offsetY:Number = (position.y - area.y);
			return new Point(offsetX, offsetY);
		}
		
		public function get area():Rectangle { return _area; }
		public function set area(value:Rectangle):void 
		{
			_area = value.clone();
			percentage = new Point(percentageX, percentageY);
		}
	}

}